package com.yoyo.yyadsdk.serv;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.dollkey.hdownload.activity.AdWebViewActivity;
import com.yoyo.yyadsdk.R;
import com.yoyo.yyadsdk.api.IConfigApi;
import com.yoyo.yyadsdk.bean.DayWordBean;
import com.yoyo.yyadsdk.bean.dao.AdvScreenEntity;
import com.yoyo.yyadsdk.config.Constants;
import com.yoyo.yyadsdk.config.PullFeature;
import com.yoyo.yyadsdk.util.AdvUtils;
import com.yoyo.yyadsdk.util.AnalysisUtils;
import com.yoyo.yyadsdk.util.ApiManage;
import com.yoyo.yyadsdk.util.DensityUtil;
import com.yoyo.yyadsdk.util.TimeUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.yoyo.yyadsdk.config.Constants.SUCCESS;

public class WindowBUService extends Service {

    private Context mContext;
    protected int mWidth;
    protected int mHeight;

    private WindowManager wManager;// 窗口管理者
    protected WindowManager.LayoutParams mParams;// 窗口的属性
    private View inflate;
    private String mAty;
    private DayWordBean.RespDataBean mRespData;
    private Disposable mDisposable;
    private boolean flag = true;
    private Handler mHandler = new Handler();
    private Runnable mRunnable;
    private AdvScreenEntity mAdv;

    @Override
    public void onCreate() {
        mContext = this;
        wManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        mParams = new WindowManager.LayoutParams();
        mParams.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;// 系统提示window TYPE_SYSTEM_ALERT  /  锁屏TYPE_SYSTEM_ERROR
        mParams.format = PixelFormat.TRANSLUCENT;// 支持透明
        mParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// 焦点
        DisplayMetrics outMetrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wManager.getDefaultDisplay().getRealMetrics(outMetrics);
        } else {
            wManager.getDefaultDisplay().getMetrics(outMetrics);
        }
        mWidth = outMetrics.widthPixels;
        mHeight = outMetrics.heightPixels;
        //mParams.format = PixelFormat.RGBA_8888;
        //mParams.alpha = 0.1f;//窗口的透明度
        mParams.gravity = Gravity.TOP;
        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;//窗口的宽和高
        mParams.height = DensityUtil.dp2px(this, 122);
        mParams.windowAnimations = R.style.BUAnimationTheme;

        inflate = LayoutInflater.from(this).inflate(R.layout.common_banner_, null);
        ViewGroup container = inflate.findViewById(R.id.content_contains);
        container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mRespData != null) {
                    if (mRespData.getType() == 1)
//                        AdWebViewActivity.toBrowser(mContext, "https://today.ttlaosiji.cn/?qid=L11&?ADTAG=kp.sp");
                        AdWebViewActivity.newInstance(mContext, "https://today.ttlaosiji.cn/?qid=L11&?ADTAG=kp.sp", false);
                    else {
//                        AdWebViewActivity.toBrowser(mContext, mRespData.getToUrl());
                        AdWebViewActivity.newInstance(mContext, mRespData.getToUrl(), mRespData.getType(), AnalysisUtils.POSITION_LOCK, mRespData.getContentId(), false);
                        AnalysisUtils.addStatistics(mContext, mRespData.getType(), AnalysisUtils.POSITION_LOCK, AnalysisUtils.TYPE_CLICK, mRespData.getContentId());
                    }
                }
            }
        });
        registerBroadcast();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (flag) {
            flag = false;
            mAty = intent.getStringExtra("aty");
            mAdv = intent.getParcelableExtra("adv");
            loadDayWord();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private DismissReceiver mDismissReceiver;

    private void registerBroadcast() {
        //注册接收异常广播消息
        mDismissReceiver = new DismissReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(com.yoyo.yyadsdk.broad.DismissReceiver.ACTION);
        registerReceiver(mDismissReceiver, filter);
    }

    @Override
    public void onDestroy() {
        if (inflate.getParent() != null)
            wManager.removeView(inflate);//移除窗口
        unregisterReceiver(mDismissReceiver);
        if (mHandler != null) {
            if (mRunnable != null) {
                mHandler.removeCallbacks(mRunnable);
                mRunnable = null;
            }
            mHandler = null;
        }
        if (!mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        super.onDestroy();
    }

    private void loadDayWord() {
        mDisposable = ApiManage.getInstance().getApi("https://lock.ttlaosiji.cn:8082/", IConfigApi.class)
                .getDayWord(Constants.MEDIA_ID)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<DayWordBean>() {
                    @Override
                    public void accept(DayWordBean updateBean) {
                        if (updateBean.getResp_status().equals(SUCCESS)) {
                            TextView fortuneTv;
                            TextView wordTv;
                            TextView authorTv;
                            TextView newsDateTv;
                            TextView sourceTv;
                            ImageView newsIv;
                            mRespData = updateBean.getResp_data();
                            switch (mRespData.getType()) {
                                case 1: //每日一言
                                    ((ViewStub) inflate.findViewById(R.id.day_word_item)).inflate();
                                    fortuneTv = inflate.findViewById(R.id.fortune_tv);
                                    wordTv = inflate.findViewById(R.id.word_tv);
                                    authorTv = inflate.findViewById(R.id.author_tv);

                                    fortuneTv.setText(mRespData.getDayWord().getFortune());
                                    wordTv.setText(mRespData.getDayWord().getWord());
                                    authorTv.setText("- - ".concat(mRespData.getDayWord().getAuthor()));
                                    break;
                                case 2: //历史上的今天
                                    ((ViewStub) inflate.findViewById(R.id.history_item)).inflate();
                                    wordTv = inflate.findViewById(R.id.word_tv);
                                    newsDateTv = inflate.findViewById(R.id.news_date_tv);

                                    String[] title = mRespData.getTitle().split(" ");
                                    wordTv.setText(title[1]);
                                    newsDateTv.setText(title[0]);
                                    break;
                                case 3: //新闻
                                case 4: //视频
                                    ((ViewStub) inflate.findViewById(R.id.news_item)).inflate();
                                    newsIv = inflate.findViewById(R.id.news_iv);
                                    sourceTv = inflate.findViewById(R.id.source_tv);
                                    wordTv = inflate.findViewById(R.id.word_tv);
                                    Glide.with(newsIv).load(mRespData.getCover()).into(newsIv);
                                    wordTv.setText(mRespData.getTitle());
                                    sourceTv.setText(mRespData.getSource());
                                    break;
                            }
                            AnalysisUtils.addStatistics(mContext, mRespData.getType(), AnalysisUtils.POSITION_BANNER, AnalysisUtils.TYPE_LOAD, mRespData.getContentId());
                            loadSuccess();
                        } else {
                            loadFail();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        loadFail();
                    }
                });
    }

    protected void loadSuccess() {
        wManager.addView(inflate, mParams);//添加窗口
        long duration = mAdv.getDuration();
        //记录本地数据
        AdvUtils.recordAdvExposed(mAdv.getId(), PullFeature.ADV_BANNER_UP_);
        //延时关闭
        if (duration > 0) {
            mRunnable = new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            };
            mHandler.postDelayed(mRunnable, duration * TimeUtils.SECOND);
        }
    }

    protected void loadFail() {
        //记录本地数据
        AdvUtils.recordAdvExposed(mAdv.getId(), PullFeature.ADV_BANNER_UP_);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public class DismissReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && com.yoyo.yyadsdk.broad.DismissReceiver.ACTION.equals(intent.getAction())) {
                String aty = intent.getStringExtra("aty");
                if (!aty.equals(mAty)) {
                    stopSelf();
                }
            }
        }
    }
}